define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"http://api.tianditu.gov.cn/api?v=4.0&tk=aeb17a8215786a5dd17f5f9c92bebc0c",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock, Loading){

	var getFxCasualtyLevelMapController = function(){
		return getServer() + "/fx/fxCasualtyLevelMaps";
	};


	/**
	 * 页面初始化
	 */
	var tdMap;
	var init = function(){
		initMap();
		getFxCasualtyLevelMap50_10Data();
	};


	var getFxCasualtyLevelMap50_10Data = function () {
		clearPolygons();
		loading.show();
		tdMap.closeInfoWindow();

		var formData = {province: "", city: "", area: "", extend10: "1", isHaveAuthorityControl: "1"};

		var url = getFxCasualtyLevelMapController() + "/getFxCasualtyLevelMaps";
		$.ajax({
			url: url,
			data: formData,
			//contentType: "application/json",
			type: "POST",
			success: function (result) {
				loading.close();
				if (typeof(result) == 'string') {
					Util.alert(result);
					return;
				}
				var data = result ? result.data : [];
				console.log(data);
				if (data && data.length) {
					fileName2feature = {};
					var local_points = [], affiliatedFileName;
					for (var idx = 0;idx < data.length;idx++) {

						affiliatedFileName = data[idx].affiliatedFileName;
						!fileName2feature[affiliatedFileName] && (fileName2feature[affiliatedFileName] = []);


						var coords_str = data[idx].coordinate;
						var geometries = coords_str.split("|");
						console.log(idx, "geometries: ", geometries.length);
						for (var k = 0;k < geometries.length;k++) {
							var __coords = geometries[k].split("#");
							for (var m = 0;m < __coords.length;m++) {
								var _coords = __coords[m].split(", "), points = [];
								for (var n = 0;n < _coords.length;n++) {
									var coord = _coords[n].split(" ");
									var lon = parseFloat(coord[0]), lat = parseFloat(coord[1]), lonlat = new T.LngLat(lon, lat);
									points.push(lonlat);
									local_points.push(lonlat);
								}
								var polygon = new T.Polygon(points, {
									color: "#860404",
									weight: 1,
									opacity: 0.5,
									fillColor: rank_color[data[idx].level + ""],
									fillOpacity: 0.7,
									affiliatedFileName: data[idx].affiliatedFileName,
									level: data[idx].level,
									district: data[idx].province + data[idx].city + data[idx].area
								});
								polygon.addEventListener("mouseover", function (obj) {
									console.log(obj);
									var target = obj.target, bounds = target.getBounds(), center = bounds.getCenter(), district = target.options.district;
									global_infoWin.setContent(district + ": " + target.options.level);
									tdMap.openInfoWindow(global_infoWin, center);
								});
								global_polygons.push(polygon);
								fileName2feature[affiliatedFileName].push(polygon);
							}
						}
					}
					filterLargeNumberPolygons();
					tdMap.setViewport(local_points);
				} else {
					Util.alert("查询无数据!");
				}
			},
			error: function(xhr, state, errorThrown){
				loading.close();
				Util.alert("查询数据出现异常: " + xhr.statusText);
			}
		});
	};


	var fileName2feature = {};
	var global_polygons = [];
	//var rank_color = {"1": "#A87001", "2": "#DF9E66", "3": "#F6C568", "4": "#FFEABD", "5": "#FFFFBF"};
	var rank_color = {"1": "#B2001F", "2": "#DF0029", "3": "#EE7C6B", "4": "#F5A89A", "5": "#FCDAD5"};
	var loading = Loading({text : "正在查询数据..."});
	var global_infoWin = new T.InfoWindow("");
	var initMap = function() {
        var mapH = document.body.clientHeight - $(".pd-search-container").height() - 10;
        $("#fxCasualtyLevelMap").height(mapH);

        var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
            projection: 'EPSG:4326',
            minZoom: 4,
            layers: [vec_layer, cva_layer]
        };
        tdMap = new T.Map('fxCasualtyLevelMap', config), zoom = 4;
        tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

        var control=new T.Control.Zoom();
        tdMap.addControl(control);

        //创建比例尺控件对象
        var scale = new T.Control.Scale();
        tdMap.addControl(scale);

		//rectTool = new T.RectangleTool(tdMap);

		tdMap.addEventListener("zoomend", filterLargeNumberPolygons);
		tdMap.addEventListener("moveend", filterLargeNumberPolygons);
	};
	var clearPolygons = function () {
		_clearPolygons();
		global_polygons = [];
	};
	var _clearPolygons = function () {
		for (let i = 0; i < global_polygons.length; i++) {
			tdMap.removeOverLay(global_polygons[i]);
		}
	};

	var filterLargeNumberPolygons = function (e) {
		if (!e) return;
		if (e.type == "zoomend") return;
		var suit_num = 1000, suit_zoom = 10, zoom = tdMap.getZoom();
		_clearPolygons();
		var bounds = tdMap.getBounds(), sw = bounds.getSouthWest(), ne = bounds.getNorthEast();
		var cPoints = [{x: sw.lat, y: sw.lng}, {x: ne.lat, y: sw.lng}, {x: ne.lat, y: ne.lng}, {x: sw.lat, y: ne.lng}];
		var lng_lats, _lng_lats, _global_polygons = [];
		for (const eKey in fileName2feature) _global_polygons = _global_polygons.concat(fileName2feature[eKey]);
		for (let i = 0; i < _global_polygons.length; i++) {
			lng_lats = _global_polygons[i].getLngLats();
			var points = [];
			for (let j = 0; j < lng_lats.length; j++) {
				_lng_lats = lng_lats[j];
				var _points = [];
				for (let k = 0; k < _lng_lats.length; k++) {
					_points.push({x: _lng_lats[k].lat, y: _lng_lats[k].lng});
				}
				points.push(_points);
			}
			for (let l = 0; l < points.length; l++) {
				var _points = points[l];
				if (zoom >= suit_zoom) {
					if (isPolygonsOverlap(cPoints, _points)) {
						tdMap.addOverLay(_global_polygons[i]);
						suit_num--;
					} else {
						tdMap.removeOverLay(_global_polygons[i]);
					}
				} else {
					if (suit_num > 0) {
						if (isPolygonsOverlap(cPoints, _points)) {
							tdMap.addOverLay(_global_polygons[i]);
							suit_num--;
						} else {
							tdMap.removeOverLay(_global_polygons[i]);
						}
					} else {
						return;
					}
				}
			}
		}
		console.log("size:", (1000 - suit_num), "zoom: ", zoom);
	};
	var isPolygonsOverlap = function (plyA, plyB) {
		return isPolygonsIntersectant(plyA, plyB) || isPointInPolygonBidirectional(plyA, plyB);
	}
	//判断两多边形线段是否相交
	var isSegmentsIntersectant = function (segA, segB) {//线线
		const abc = (segA[0].x - segB[0].x) * (segA[1].y - segB[0].y) - (segA[0].y - segB[0].y) * (segA[1].x - segB[0].x);
		const abd = (segA[0].x - segB[1].x) * (segA[1].y - segB[1].y) - (segA[0].y - segB[1].y) * (segA[1].x - segB[1].x);
		if (abc * abd >= 0) {
			return false;
		}
		const cda = (segB[0].x - segA[0].x) * (segB[1].y - segA[0].y) - (segB[0].y - segA[0].y) * (segB[1].x - segA[0].x);
		const cdb = cda + abc - abd;
		return !(cda * cdb >= 0);
	}
	//判断两多边形边界是否相交
	var isPolygonsIntersectant = function (plyA, plyB) {//面面
		for (let i = 0, il = plyA.length; i < il; i++) {
			for (let j = 0, jl = plyB.length; j < jl; j++) {
				const segA = [plyA[i], plyA[i === il - 1 ? 0 : i + 1]];
				const segB = [plyB[j], plyB[j === jl - 1 ? 0 : j + 1]];
				if (isSegmentsIntersectant(segA, segB)) {
					return true;
				}
			}
		}
		return false;
	}
	//判断点是否在另一平面图中
	var isPointInPolygon = function (point, polygon) {

		//下述代码来源：http://paulbourke.net/geometry/insidepoly/，进行了部分修改
		//基本思想是利用射线法，计算射线与多边形各边的交点，如果是偶数，则点在多边形外，否则
		//在多边形内。还会考虑一些特殊情况，如点在多边形顶点上，点在多边形边上等特殊情况。

		var N = polygon.length;
		var boundOrVertex = true; //如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
		var intersectCount = 0; //cross points count of x
		var precision = 2e-10; //浮点类型计算时候与0比较时候的容差
		var p1, p2; //neighbour bound vertices
		var p = point; //测试点

		p1 = polygon[0]; //left vertex
		for (var i = 1; i <= N; ++i) { //check all rays
			if (p.x == p1.x && p.y == p1.y) {
				return boundOrVertex; //p is an vertex
			}

			p2 = polygon[i % N]; //right vertex
			if (p.y < Math.min(p1.y, p2.y) || p.y > Math.max(p1.y, p2.y)) { //ray is outside of our interests
				p1 = p2;
				continue; //next ray left point
			}

			if (p.y > Math.min(p1.y, p2.y) && p.y < Math.max(p1.y, p2.y)) { //ray is crossing over by the algorithm (common part of)
				if (p.x <= Math.max(p1.x, p2.x)) { //x is before of ray
					if (p1.y == p2.y && p.x >= Math.min(p1.x, p2.x)) { //overlies on a horizontal ray
						return boundOrVertex;
					}

					if (p1.x == p2.x) { //ray is vertical
						if (p1.x == p.x) { //overlies on a vertical ray
							return boundOrVertex;
						} else { //before ray
							++intersectCount;
						}
					} else { //cross point on the left side
						var xinters = (p.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x; //cross point of x
						if (Math.abs(p.x - xinters) < precision) { //overlies on a ray
							return boundOrVertex;
						}

						if (p.x < xinters) { //before ray
							++intersectCount;
						}
					}
				}
			} else { //special case when ray is crossing through the vertex
				if (p.y == p2.y && p.x <= p2.x) { //p crossing over p2
					var p3 = polygon[(i + 1) % N]; //next vertex
					if (p.y >= Math.min(p1.y, p3.y) && p.y <= Math.max(p1.y, p3.y)) { //p.y lies between p1.y & p3.y
						++intersectCount;
					} else {
						intersectCount += 2;
					}
				}
			}
			p1 = p2; //next ray left point
		}

		if (intersectCount % 2 == 0) { //偶数在多边形外
			return false;
		} else { //奇数在多边形内
			return true;
		}
	}
	//判断两多变形是否存在点与区域的包含关系(A的点在B的区域内或B的点在A的区域内)
	var isPointInPolygonBidirectional = function (plyA, plyB) {//面面
		let [a, b] = [false, false];
		a = plyA.some(item => isPointInPolygon(item, plyB));
		if (!a) {
			b = plyB.some(item => isPointInPolygon(item, plyA));
		}
		return a || b;
	}

	return {
		init:init
	};
});
